<template>
  <div>
    <h1>hello</h1>
    <!-- 语音 -->
    <i class="el-icon-microphone"  @click = 'handleBtnClick' ></i>
     <audio controls autoplay id="audio"></audio>
    <ButtonGroup size='small' >
       <Button @click="play_mp3">播放</Button>
      <Button @click="send_voice">发送</Button>
      <Button @click="cancel_mp3">停止</Button>
       <Button @click="cancel">取消</Button>
    </ButtonGroup>
  </div>


</template>
<script>
import axios from 'axios'
import Recorderx, { ENCODE_TYPE } from "recorderx";
const rc = new Recorderx();

export default {
  components:{},
  props:{},
  data(){
    return{
      chatList:[], // 聊太难信心的展示区域
      uuid:'', // 生成的随机数
      content:'', // 聊天信息
      topic:[], // 信息详情
      imageUrl:'', // 发送的图片
      fileList:[], // 文件列表
      mp4:"" // 后缀格式
    }
  },
  methods: {
    //录制语音
    handleBtnClick: function () {
      let that = this
      that.news_img = !that.news_img
      rc.start().then(() => {
          that.news_img = !that.news_img
          console.log("start recording");
        })
        .catch(error => {
          alert('获取麦克风失败')
          console.log("Recording failed.", error);
        });
    },
//暂停语音
    cancel_mp3: function() {
      rc.pause();
    },
//取消语音
cancel: function() {
  rc.clear();

},
//播放语音
play_mp3:function(){
  var wav = rc.getRecord({
  encodeTo: ENCODE_TYPE.WAV,
  compressible: true
});
document.getElementById('audio').src = URL.createObjectURL(wav);
},
//发送语音
    send_voice: function () {
      let that = this
      var wav = rc.getRecord({
        encodeTo: ENCODE_TYPE.WAV,
        compressible: true
      });
      const uuid = this.uuid;

      if (this.chatList !== "") {
        var end_time = this.chatList[this.chatList.length - 1];
      }
      console.log("3发送消息了")

      var formData = new FormData();
      formData.append('file',wav);
      formData.append('topic_id',uuid);
      formData.append('last_time',end_time);
      formData.append('type',5);
      formData.append("file", wav,Date.parse(new Date())+".wav");
      let headers = {headers: {"Content-Type": "multipart/form-data"}}
      axios.defaults.withCredentials=true
      axios.post("/api/voice", formData, headers).then((data) => {
        console.log(data)
        that.news_img = !that.news_img;
        // this.reload();
        rc.clear();
      }).catch(err => {
          console.log(err);
        });
 // this.$request({
 //        url: "/api/voice",
 //        method: "post",
 //        data:formData,
 //       headers: {"Content-Type": "multipart/form-data"}
 //      }).then((data) => {
 //          console.log(data)
 //          that.news_img = !that.news_img
 //          this.content = "";
 //        })
 //        .catch(err => {
 //          console.log(err);
 //        });
    },
  }

}
</script>
<style>

</style>
